package com.social.instadownloader.network.download;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.widget.Toast;

import com.social.instadownloader.activity.MainActivity;
import com.social.instadownloader.network.download.DownloadTask.OnDownloadListener;
import com.social.instadownloader.screen.HistoryScreen;
import com.social.instadownloader.util.InstaFileManager;
import com.social.instadownloader.util.SdcardUtils;

public class DownloadWithProgress {

	private Activity mActivity;
	
	public DownloadWithProgress(Activity activity){
		mActivity = activity;
	}
	
	public boolean runDownload(String url, String fileName){
		boolean ret = true;
		if(SdcardUtils.hasStorage()){
			String absolutePath = InstaFileManager.INSTA_DOWNLOADER_FOLDER + fileName;
			new DownloadTask(url, absolutePath, mDownloadListener,null).execute();
		}else{
			ret = false;
		}
		return ret;
	}
	
	ProgressDialog barProgressDialog;

    @SuppressWarnings("deprecation")
    private ProgressDialog getProgressDialog() {
        if (barProgressDialog == null) {
            barProgressDialog = new ProgressDialog(mActivity);
            barProgressDialog.setTitle("Downloading...");
            barProgressDialog.setMessage("Download in progress ...");
            barProgressDialog.setProgressStyle(barProgressDialog.STYLE_HORIZONTAL);
            barProgressDialog.setProgress(0);
            barProgressDialog.setMax(100);
        }
        return barProgressDialog;
    }

    // @Override
    public void onChanging(final double value) {
        if (barProgressDialog == null || !barProgressDialog.isShowing()) {
            getProgressDialog().show();
        }
        try {
            // barProgressDialog.incrementProgressBy((int) value);
            getProgressDialog().setProgress((int) value);
            if (barProgressDialog.getProgress() == barProgressDialog.getMax()) {
                getProgressDialog().dismiss();
            }
        } catch (Exception e) {}
    }
    
    public OnDownloadListener mDownloadListener = new OnDownloadListener() {

        @Override
        public void onProcessUpdate(int process) {
            if (barProgressDialog.isShowing()) onChanging(process);
        }

        @Override
        public void onDownloadSucess(String absolutePath) {
            if (mActivity instanceof MainActivity) {
            	HistoryScreen.NEED_RELOAD = true;
				((MainActivity)mActivity).changeCurrentTab(2);
				((MainActivity)mActivity).onDownloadSucess(absolutePath);
			}
        }

        @Override
        public void onDownloadPrepare() {
            onChanging(0);
        }

        @Override
        public void onDownloadFail(String fail) {
            if (barProgressDialog.isShowing()) {
                barProgressDialog.dismiss();
            }
            Toast.makeText(mActivity, "Download Fail...!", Toast.LENGTH_SHORT).show();
        }
    };
}
